//
//  HXNotifyDetailsHeaderView.m
//  KD
//
//  Created by ifly on 16/3/10.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXMeetingNotifyDetailsHeaderView.h"
#import "UIImageView+WebCache.h"
#import <AVFoundation/AVFoundation.h>
#import "QRCodeController.h"

@interface HXMeetingNotifyDetailsHeaderView()<BMKMapViewDelegate,BMKLocationServiceDelegate>
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *placeLabel;
@property (weak, nonatomic) IBOutlet UILabel *meetingTimeLabel;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;//签到
@property (weak, nonatomic) IBOutlet UIButton *outBtn;//退场
@property (weak, nonatomic) IBOutlet UIView *meetingReturnView;
@property (weak, nonatomic) IBOutlet UILabel *mettingReturnLabel;
@property (weak, nonatomic) IBOutlet UILabel *mettingReturnPersonLabel;
@property (weak, nonatomic) IBOutlet UILabel *meetingReturnPhoneLabel;

@property (weak, nonatomic) IBOutlet UIImageView *oneImageView;
@property (weak, nonatomic) IBOutlet UIImageView *twoImageView;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (weak, nonatomic) IBOutlet UIButton *questionOneBtn;
@property (weak, nonatomic) IBOutlet UILabel *questionOneLabel;
@property (weak, nonatomic) IBOutlet UIButton *questionTwoBtn;
@property (weak, nonatomic) IBOutlet UILabel *questionTwoLabel;
@property (weak, nonatomic) IBOutlet BMKMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *addSizeView;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;
@property (weak, nonatomic) IBOutlet UIButton *addBtn;
@property (weak, nonatomic) IBOutlet UIButton *reduceBtn;
@property (weak, nonatomic) IBOutlet UIButton *meetingLocationBtn;
@property(nonatomic,assign) BMKCoordinateSpan span;
@property(nonatomic,strong) BMKLocationService *location;
@property(nonatomic,assign) CLLocationCoordinate2D meetingLocation;
@property(nonatomic,assign) CLLocationCoordinate2D userLocation;

@property(nonatomic,assign) NSInteger isUserLocation;
@property(nonatomic,assign) NSInteger ismeetingLocation;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentLabelHeigth;
@end

@implementation HXMeetingNotifyDetailsHeaderView

- (void)awakeFromNib{
    self.addSizeView.layer.borderWidth = 1;
    self.addSizeView.layer.cornerRadius = 4;
    self.addSizeView.layer.borderColor = HXCustomColor(204, 204, 204, 1).CGColor;
    self.addSizeView.layer.masksToBounds = YES;
    self.lineView.backgroundColor = HXCustomColor(204, 204, 204, 1);
    self.meetingLocationBtn.layer.cornerRadius = 22.5;
    
    self.mapView.delegate = self;
//    CLLocationCoordinate2D center =  (CLLocationCoordinate2D){36.063697,120.405119 }; //坐标

    self.isUserLocation = 0;
    self.ismeetingLocation = 0;
    self.mapView.showsUserLocation = YES;//显示定位图层
    [self location];
    
    if ([[UserDefaultHandler getUserDetault:kUsers_Kind] integerValue] == UserTypeManage){
        [self.registerBtn removeFromSuperview];
        [self.outBtn removeFromSuperview];
        [self.meetingReturnView removeFromSuperview];
        [self.mettingReturnLabel removeFromSuperview];
        [self.mettingReturnPersonLabel removeFromSuperview];
        [self.meetingReturnPhoneLabel removeFromSuperview];
    }else{
    }
}

-(void)setMeetingType:(NSString *)meetingType{
    _meetingType = meetingType;
    if (![_meetingType isEqualToString:@"qiye"]) {
        [self.meetingReturnView removeFromSuperview];
    }
}

- (void)setData:(HXNotifyDetailsModel *)data{
    _data = data;
    if ([[UserDefaultHandler getUserDetault:kUsers_Kind] integerValue] == UserTypeCorp) {
        
        if ([_data.state.isCome isEqualToString:@"1"]) {
            
            [_registerBtn setEnabled:NO];
            _registerBtn.backgroundColor = [UIColor lightGrayColor];
            [_registerBtn setTitle:@"已签到" forState:UIControlStateNormal];
            _registerBtn.titleLabel.font = [UIFont systemFontOfSize:10];
        }
        if ([_data.state.isGo isEqualToString:@"1"]) {
            
            [_outBtn setEnabled:NO];
            _outBtn.backgroundColor = [UIColor lightGrayColor];
            [_outBtn setTitle:@"已退场" forState:UIControlStateNormal];
            _outBtn.titleLabel.font = [UIFont systemFontOfSize:10];
        }
        
        if ([data.details.MU_IsJoin isEqualToString:@"1"]) {//本人参会
            self.mettingReturnPersonLabel.text = @"本人参会";
            self.meetingReturnPhoneLabel.text = @"";
        }else{
            self.mettingReturnPersonLabel.text = data.details.MU_ReplaceMan;
            self.meetingReturnPhoneLabel.text = data.details.MU_ReplaceManTel;
        }
    }
    self.isUserLocation = 0;
    self.ismeetingLocation = 0;
    self.mapView.scrollEnabled = NO;
    if ([GlobalUtil isNilValue:data.details.MessAdd]) {
        self.placeLabel.text = [NSString stringWithFormat:@"开会地点:暂无"];
        
    }else{
        self.placeLabel.text = [NSString stringWithFormat:@"开会地点:%@",data.details.MessAdd];
    }
    
    if ([GlobalUtil isNilValue:data.details.Title]) {
        self.titleLabel.text = @"暂无标题";
    }else{
        self.titleLabel.text = data.details.Title;
    }
    
    if ([GlobalUtil isNilValue:data.details.EndDate]) {
        self.endTimeLabel.text = [NSString stringWithFormat:@"截止时间:暂无"];
        
    }else{
        self.endTimeLabel.text = [NSString stringWithFormat:@"截止时间:%@",data.details.EndDate];
    }

    if ([GlobalUtil isNilValue:data.details.Content]) {
        self.contentLabel.text = @"暂无内容";
    }else{
        self.contentLabel.text = data.details.Content;
    //self.contentLabel.text = @"self.contentLabel.text = data.details.Content;self.contentLabel.text = data.details.Content;self.contentLabel.text = data.details.Content;self.contentLabel.textta.details.Content;self.contentLabel.text = data.details.Content;";
    }
    
    if ([GlobalUtil isNilValue:data.details.OpenDate]) {
        self.meetingTimeLabel.text = [NSString stringWithFormat:@"开会时间:暂无"];
    }else{
        self.meetingTimeLabel.text = [NSString stringWithFormat:@"开会时间:%@",data.details.OpenDate];
    }
    if ([GlobalUtil isNilValue:data.details.MessX]||[GlobalUtil isNilValue:data.details.MessY]) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"此会议开会地点读取失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
    }else{
        self.ismeetingLocation = 1;
        self.meetingLocation =  (CLLocationCoordinate2D){[data.details.MessY doubleValue],[data.details.MessX doubleValue]};
        BMKCoordinateSpan span = BMKCoordinateSpanMake(0.005686, 0.009705);//跨度(经纬度)
        BMKCoordinateRegion region = BMKCoordinateRegionMake(self.meetingLocation, span);//位置结构体
        [self.mapView setRegion:region animated:YES];
        [self addAnnoWithPT:self.meetingLocation andTitle:@"会议地点" andAddress:@""];
    }
    if (data.questlist.count>0) {
        HXNotifyDetailsQuestListModel *quesOne = data.questlist[0];
        self.questionOneLabel.text = quesOne.Que_Content;
    }else{
        self.questionOneLabel.text = @"暂无";
        [self.questionOneBtn removeFromSuperview];
    }
    if (data.questlist.count>1) {
        HXNotifyDetailsQuestListModel *quesTwo = data.questlist[1];
        self.questionTwoLabel.text = quesTwo.Que_Content;
    }else{
        self.questionTwoLabel.text = @"暂无";
        [self.questionTwoBtn removeFromSuperview];
    }
    if (data.piclist.count>0) {
        HXNotifyDetailsPictListModel *pictOne = data.piclist[0];
        [self.oneImageView sd_setImageWithURL:[NSURL URLWithString:pictOne.Files_Path] placeholderImage:[UIImage imageNamed:@"loading"] options:SDWebImageRetryFailed|SDWebImageLowPriority|SDWebImageCacheMemoryOnly completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (error) {
                self.oneImageView.image = [UIImage imageNamed:@""];
            }
        }];
    }else{
        self.oneImageView.image = [UIImage imageNamed:@""];
    }
    if (data.piclist.count>1) {
        HXNotifyDetailsPictListModel *pictTwo = data.piclist[1];
        [self.twoImageView sd_setImageWithURL:[NSURL URLWithString:pictTwo.Files_Path] placeholderImage:[UIImage imageNamed:@"loading"] options:SDWebImageRetryFailed|SDWebImageLowPriority|SDWebImageCacheMemoryOnly completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (error) {
                self.twoImageView.image = [UIImage imageNamed:@""];
            }
        }];
    }else{
        self.twoImageView.image = [UIImage imageNamed:@""];
    }
    
    [self layoutIfNeeded];
}

- (IBAction)addBtnClick:(id)sender {
     [self.mapView zoomIn];
}
- (IBAction)reduceBtnClick:(id)sender {
    [self.mapView zoomOut];
}

-(NSInteger)judgeItsTimeToMetting {
    
    //本地现在时间
    NSString * nowPhoneTime = [GlobalUtil getNowPhoneTime];
    //NSDate * nowTimeDate = [NSDate dateWithTimeIntervalSinceNow:<#(NSTimeInterval)#>]
    
    NSString * beginMettingTime = _data.details.OpenDate;
    
    NSInteger judgeNum = [GlobalUtil compareDate:nowPhoneTime withDate:beginMettingTime];
    
    if (judgeNum != 1) {
        //可以签到
        
    }
    return judgeNum;
}

/**
 是否可以打开设置页面
 */
- (BOOL)canOpenSystemSettingView {
    if (IS_VAILABLE_IOS8) {
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            return YES;
        }else {
            return NO;
        }
    }else {
        return NO;
    }
}
/**
 调到系统设置页面
 */
- (void)systemSettingView {
    if (IS_VAILABLE_IOS8) {
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}


/**
 调用系统相机 扫描二维码  //------2016.9.26 修改-------\\
 */
- (void)createFunctionByCamere {
    
    NSString * mdeiaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mdeiaType];
    if (authStatus == AVAuthorizationStatusDenied) {
        if (IS_VAILABLE_IOS8) {
            
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"相机权限受限" \
                                                                            message:@"请在iPhone的\"设置->隐私->相机\"选项中,允许\"建管通\"访问您的相机."
                                                                     preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"好"
                                                      style:UIAlertActionStyleCancel
                                                    handler:^(UIAlertAction * _Nonnull action) {
                                                        
                                                    }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"去设置"
                                                      style:UIAlertActionStyleDefault
                                                    handler:^(UIAlertAction * _Nonnull action) {
                                                        if ([self canOpenSystemSettingView]) {
                                                            [self systemSettingView];
                                                        }
                                                    }]];
            [[self viewController] presentViewController:alert animated:YES completion:^{
            }];
            //[self presentViewController:alert animated:YES completion:nil];
        }else {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"相机权限受限"
                                                             message:@"请在iPhone的\"设置->隐私->相机\"选项中,允许\"建管通\"访问您的相机." delegate:nil
                                                   cancelButtonTitle:@"好的"
                                                   otherButtonTitles:nil];
            [alert show];
        }
        return;
    }
    
    QRCodeController * qrCodeVc = [[QRCodeController alloc] init];
    qrCodeVc.view.alpha = 0;
    [qrCodeVc setDidReceiveBlock:^(NSString *result) {
        NSLog(@"%@",result);
        
        //返回扫描结果 判断 并进行网络签到
        
    }];
    AppDelegate * appDele = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDele.window.rootViewController addChildViewController:qrCodeVc];
    [appDele.window.rootViewController.view addSubview:qrCodeVc.view];
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         qrCodeVc.view.alpha = 1;
                     } completion:^(BOOL finished) {
                         
                     }];
}


/**签到按钮*/
- (IBAction)registerBtnClick:(id)sender {
    
    if (self.isUserLocation != 1) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"定位失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
    if (self.ismeetingLocation != 1) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"无会议位置" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
    if (self.messageDict == nil) {
        [SVProgressHUD showErrorWithStatus:@"签到失败,该会议通知有误"];
        return;
    }
    //NSInteger judgeNum = [self judgeItsTimeToMetting];
    BMKMapPoint point1 = BMKMapPointForCoordinate(self.userLocation);
    BMKMapPoint point2 = BMKMapPointForCoordinate(self.meetingLocation);
    CLLocationDistance distance = BMKMetersBetweenMapPoints(point1,point2);
    if (distance>222) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"签到失败" message:@"请到达地点后重试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
//    else if ([self judgeItsTimeToMetting] == 1) {
//        //不能签到
//        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"签到失败" message:@"请到达开会时间后重试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        [alert show];
//        return;
//    }
    else{
        
        [self createFunctionByCamere];
        
        [NetworkAPI reachWithMessID:[self.messageDict objectForKey:@"data.MessageID"]
                             UserId:[self.messageDict objectForKey:@"data.TMUserID"] SignType:@"0" success:^(HXBaseModel *result) {
                                 if ([result.code isEqualToString:@"200"]) {
                                     [SVProgressHUD showSuccessWithStatus:@"签到成功"];
                                     self.registerBtn.enabled = NO;
                                     [self.registerBtn setTitle:@"已签到" forState:UIControlStateNormal];
                                     self.registerBtn.titleLabel.font = [UIFont systemFontOfSize:10];
                                     self.registerBtn.backgroundColor = [UIColor lightGrayColor];
                                 }else if([result.code isEqualToString:@"400"]){
                                     [SVProgressHUD showSuccessWithStatus:@"已经签到过了"];
                                     self.registerBtn.enabled = NO;
                                     [self.registerBtn setTitle:@"已签到" forState:UIControlStateNormal];
                                     self.registerBtn.titleLabel.font = [UIFont systemFontOfSize:10];
                                     self.registerBtn.backgroundColor = [UIColor lightGrayColor];
                                 }else{
                                     [SVProgressHUD showErrorWithStatus:@"签到失败"];
                                 }
                             } failure:^(NSError *err) {
                                 [SVProgressHUD showErrorWithStatus:@"网络错误"];
                             }];
   }
}
/**退场按钮*/
- (IBAction)outBtnClick:(id)sender {
    
    if ([_data.state.isCome isEqualToString:@"1"]) {
        [NetworkAPI reachWithMessID:[self.messageDict objectForKey:@"data.MessageID"]
                             UserId:[self.messageDict objectForKey:@"data.TMUserID"] SignType:@"1" success:^(HXBaseModel *result) {
                                 if ([result.code isEqualToString:@"200"]) {
                                     [SVProgressHUD showSuccessWithStatus:@"退场成功"];
                                     self.outBtn.enabled = NO;
                                     [self.outBtn setTitle:@"已退场" forState:UIControlStateNormal];
                                     self.outBtn.titleLabel.font = [UIFont systemFontOfSize:10];
                                     self.outBtn.backgroundColor = [UIColor lightGrayColor];
                                 }else if([result.code isEqualToString:@"400"]){
                                     [SVProgressHUD showSuccessWithStatus:@"已经退场了"];
                                     self.outBtn.enabled = NO;
                                     [self.outBtn setTitle:@"已退场" forState:UIControlStateNormal];
                                     self.outBtn.titleLabel.font = [UIFont systemFontOfSize:10];
                                     self.outBtn.backgroundColor = [UIColor lightGrayColor];
                                 }else{
                                     [SVProgressHUD showErrorWithStatus:@"退场失败"];
                                 }
                             } failure:^(NSError *err) {
                                 [SVProgressHUD showErrorWithStatus:@"网络错误"];
                             }];

    }
    else {
        //不能签退
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"签退失败" message:@"请签到之后会议结束时再签退" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
}


- (IBAction)meetingLoctionBtnClick:(id)sender {
    if (self.ismeetingLocation != 1) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"此会议开会地点读取失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
    BMKCoordinateSpan span = BMKCoordinateSpanMake(0.002093,0.003279);//跨度(经纬度)
    BMKCoordinateRegion region = BMKCoordinateRegionMake(self.meetingLocation, span);//位置结构体
    [self.mapView setRegion:region animated:YES];
}


/**添加大头针*/
- (void)addAnnoWithPT:(CLLocationCoordinate2D)coor andTitle:(NSString *)title andAddress:(NSString *)address
{
    BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
    annotation.coordinate = coor;
    annotation.title = title;
    annotation.subtitle = address;
    [self.mapView addAnnotation:annotation];
}


- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        static NSString *pinID = @"PIN";
        BMKPinAnnotationView *newAnnotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
        if (newAnnotationView == nil) {
            newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID];
        }
        newAnnotationView.annotation = annotation;
        newAnnotationView.pinColor = BMKPinAnnotationColorRed;
        newAnnotationView.animatesDrop = YES;
        return newAnnotationView;
    }
    return nil;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGSize max = CGSizeMake([UIScreen mainScreen].bounds.size.width - 28, MAXFLOAT);
    CGSize contentLabelSize = [self SizeWithString:self.contentLabel.text font:[UIFont systemFontOfSize:16] maxsize:max];
    self.contentLabelHeigth.constant = contentLabelSize.height;
    CGFloat selfHeigth = 680 + contentLabelSize.height ;
    self.height = selfHeigth;
    [self layoutIfNeeded];
}

-(CGSize)SizeWithString:(NSString*)str font:(UIFont *)font maxsize:(CGSize)maxSize
{
    NSDictionary *dict = @{NSFontAttributeName:font};
    CGSize size = [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return size;
}


#pragma mark - BMKLocationServiceDelegate
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [self.mapView updateLocationData:userLocation];
    self.userLocation = userLocation.location.coordinate;
    self.isUserLocation = 1;
}
/**
 *定位失败后，会调用此函数
 *@param error 错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"定位失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}
-(BMKLocationService *)location{
    if (!_location) {
        _location = [[BMKLocationService alloc]init];
        _location.delegate = self;
        [_location startUserLocationService];
    }
    return _location;
}

@end
